<template>
  <el-container class="page" style="overflow-x: hidden;">
    <el-header>
      <div class="flex-space-between-item">
        <div class="flex-start-item" style="padding-left: 30px;padding-top: 10px;">
          <el-avatar src="/src/assets/img/school.ico" />
          <p style="margin-left: 10px;">交大食堂</p>
          <p
            style="margin: 0 10px 0; font-size: small;background-color: red;border-radius: 5px; color: white;padding:0 5px 0;">
            {{ state ? '营业中' : '已歇业' }}</p>
          <el-switch v-model="state" class="ml-2" @change="changeStatus"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
        </div>
        <div class="flex-start-item" style="padding-top: 10px;">

          <el-popover placement="bottom" :width="150" trigger="click" show-arrow popper-style="padding:10px 0 ;" ref="popover">
            <template #reference>
              <el-button class="m-2" style="width: 150px;">{{ userInfo.name }}</el-button>
            </template>
            <p class="popover-item" @click="showModal">修改密码</p>
            <p class="popover-item" @click="exitSystem">退出</p>
          </el-popover>
        </div>
      </div>
    </el-header>
    <el-divider style="margin: 0;"></el-divider>
    <el-container>

      <el-aside width="200px">
        <el-col :span="25">

          <el-menu :router="true" style="height: calc(100vh - 62px);" default-active="/home/platform">
            <el-menu-item v-for="(item, index) in fliterRouters" :key="index" :index="item.path" ref="menuItem"
              class="flex-center-item">{{ item.name
              }}</el-menu-item>
          </el-menu>

        </el-col>
      </el-aside>

      <el-main>
        <RouterView />
      </el-main>

    </el-container>
  </el-container>
  <el-dialog v-model="dialogVisible" title="修改密码" width="30%">
    <el-form :model="formData" label-width="100px" :rules="rules" ref="modifyForm" style="padding:20px;">
      <el-form-item label="原密码：" prop="oldPwd"><el-input v-model="formData.oldPwd"></el-input></el-form-item>
      <el-form-item label="新密码：" prop="newPwd"><el-input v-model="formData.newPwd"></el-input></el-form-item>
      <el-form-item label="确认密码：" prop="confirmPwd"><el-input v-model="formData.confirmPwd"></el-input></el-form-item>
    </el-form>
    <div class="flex-end-item">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="modifyPwd(modifyForm)">确定</el-button>
    </div>

  </el-dialog>
</template>

<script setup lang="ts">

// headers
const headers = new Headers({
  'Content-Type': 'application/json',
  'token':sessionStorage.getItem('token')!,
  'Authorization':sessionStorage.getItem('token')!
})

// router menu
import { RouterView, useRouter } from 'vue-router'
const router = useRouter()
const routers = router.getRoutes()
const fliterRouters = routers.filter((item) => {
  if (item.name && item.name != 'login' && item.name != '主页') return true
  else return false
})

// menu route
import { ref, provide, reactive } from 'vue';
const state = ref(true)
const menuItem = ref(null)
provide('menuItem', menuItem)

// userInfo
import { useUserInfoStore } from '@/stores/userInfo';
const userInfo = useUserInfoStore();
// get user
let userId = sessionStorage.getItem('userId')
if (userId) {
  userId = JSON.parse(userId)
  fetch(`/api/admin/employee/${userId}`,{
    headers:headers
  }).then(res => res.json()).then(data => {
    userInfo.$patch(data.data)
  })
}



// modify pwd
const dialogVisible = ref(false)
import type { FormInstance } from 'element-plus'
const modifyForm = ref<FormInstance>()
const formData = reactive({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})
const rules = {
  oldPwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度需在6~20个字符', trigger: 'blur' },
  ],
  newPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度需在6~20个字符', trigger: 'blur' },
  ],
  confirmPwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度需在6~20个字符', trigger: 'blur' },
  ],
}
function showModal() {
  formData.oldPwd = ''
  formData.newPwd = ''
  formData.confirmPwd = ''
  dialogVisible.value = true
}
function modifyPwd(form: FormInstance | undefined) {
  if (!form) return
  form.validate((valid, fields) => {
    if (valid) {
      fetch('/api/admin/employee/editPassword', {
        method: 'PUT',
        headers: headers,
        body: JSON.stringify({
          empId: userInfo.id,
          oldPassword: formData.oldPwd,
          newPassword: formData.newPwd
        })
      }).then(res => res.json()).then(data => {
        console.log(data)
        if (data.code != 0) {
          ElMessage({
            message: "修改成功",
            type: 'success'
          })
        } else {
          ElMessage({
            message: data.msg,
            type: 'error'
          })
        }
      })
      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

// exit system
function exitSystem() {
  fetch('/api/admin/employee/logout')
  router.replace('/login')
  sessionStorage.removeItem('token')
}

fetch('/api/admin/shop/status', {
  headers:headers
}).then(res => res.json()).then(data => {
  if(data.code==1){
    state.value=data.data?true:false
  }
})
function changeStatus(){
  fetch(`/api/admin/shop/${state.value?1:0}`, {
    headers:headers,
    method:'PUT'
  }).then(res => res.json()).then(data=>{
    if(data.code==1){
      // state.value=!state.value
    }
  })
}
// popover
// import type { popover }
// const popoverRef = ref<InstanceType<typeof ElPopover>>()
</script>

<style scoped>
@import '@/assets/common.css';

.page {
  width: calc(100vw - 12px);
  height: 100vh;
}
</style>
<style>
.el-main {
  background-color: #fafafa;
  overflow-y: auto;
  position: absolute;
  left: 200px;
  top: 60px;
  width: calc(100% - 212px);
}

.el-header {
  width: calc(100% - 12px);
  position: fixed;
  border-bottom: 1px solid #e6e6e6;
  z-index: 1000;
  background-color: #fff;
}

.el-aside {
  position: fixed;
  top: 60px;
}

.popover-item {
  width: 150px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}

.popover-item:hover {
  background-color: #e6e6e6;
}
</style>
